import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import {useUserStore} from "@/store/index.js";
import {Base64} from "js-base64";

const request = axios.create({
    baseURL: "http://localhost:9601",
    timeout: 50000
})

request.interceptors.request.use(config => {
    let tokenName = localStorage.getItem("tokenName");
    if (tokenName) {
        config.headers[tokenName] = localStorage.getItem("tokenValue");
    }
    return config;
})

request.interceptors.response.use(res => {
    if (res.data.code === 401) {
        let route = router.currentRoute.value.fullPath;
        let userStore = useUserStore();
        userStore.logout();
        router.push("/login?path=" + Base64.encode(route)).then();
        return res.data;
    }
    if (res.data.code !== 200) {
        if (res.data.message) {
            ElMessage.error(res.data.message);
        }
        return Promise.reject(res.data);
    }
    return res.data;
}, res => {
    ElMessage.error("网络错误,请稍后再试")
    return Promise.reject(res);
})

export function getRequest(url, data) {
    return request.get(url, {params: data});
}

export function postRequest(url, data) {
    return request.post(url, data);
}